var JSON5 = require('json5');

const { el, mount } = redom;

function createTable(ths = [], tds = []) {
    let thr = ths.map(function(a) {
        return el('tr', a.map(function(v) {
            return el('th', v)
        }));
    });
    let tdr = tds.map(function(a) {
        return el('tr', a.map(function(v) {
            return el('td', v)
        }));
    }) 
    let thead = el('thead', [thr]);
    let tbody = el('tbody', [tdr]);
    let table = el('table', [
        thead,
        tbody
    ]);
    return table;
}


document.registerElement("aup-table", {
    prototype: Object.create(HTMLElement.prototype, {
        createdCallback: { value: function() {
            let self = this;
            this.content = `${this.children[0].innerHTML.trim()}`;
            this.$data = JSON5.parse(this.content);
            this.$table = createTable(self.$data.ths, self.$data.tds);
            this.appendChild(self.$table);
        }},
    })
});

document.registerElement("a-tab", {
    prototype: Object.create(HTMLElement.prototype, {
        createdCallback: { value: function() {
            let self = this;
            let activeRef = null;
            if (self.children[1]) {
                Array.prototype.slice.call(self.children[1].children).forEach(function(v, index) {  
                    if (v.classList.contains("active")) {
                        activeRef = v;
                    }
                    var d = document.createElement("a-tab-navitem");
                    d.addEventListener("click", function() {
                        activeRef.classList.remove("active");
                        v.classList.add("active");
                        activeRef = v;
                    });
                    d.textContent = ` ${v.textContent}`;
                    self.firstElementChild.appendChild(d);
                });   
            }                 
        }},
    })
});

document.registerElement("a-tab-navitem", {
    prototype: Object.create(HTMLElement.prototype, {
        createdCallback: { value: function() {
            let self = this;
        }},
    })
});

document.registerElement("a-tab-nasitem", {
    prototype: Object.create(HTMLElement.prototype, {
        createdCallback: { value: function() {
            let self = this;
        }},
    })
});

document.registerElement("aux-code", {
    prototype: Object.create(HTMLElement.prototype, {
        createdCallback: { value: function() {
            let self = this;
            self.innerHTML = `<pre style="max-height: 270px; overflow: auto;"><code></code></pre>`;
            fetch(`./node_modules/${self.getAttribute("src")}`).then((response) => {
                return response.text();
            }).then((text) => {
                console.log(text);
                self.children[0].children[0].innerHTML = Prism.highlight(text, Prism.languages.css);
            })
        }},
    })
});